﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Cofe.Core;
using Cofe.Core.Filter;
using Cofe.Core.Implements;
using Cofe.Data;
using Cofe.Web.Utils;

namespace Cofe.Web.Controllers.Api
{
    [Authorize]
    public class ParseController : ApiController
    {
        private string checkPath(string path)
        {
            if (path == null)
                path = "";
            path = path.Replace('/', '\\');
            return path;
        }

        // GET api/parse?path={path}&rel={rel}
        public HttpResponseMessage Get(string path, string rel = null)
        {
            Guid foundId = ControllerUtils.findEntryId(checkPath(path));
            if (foundId == Guid.Empty)
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            var response = Request.CreateResponse(HttpStatusCode.Redirect);
            string urlPath = Url.Route("DefaultEntryApi", new
            {
                httproute = "",
                controller = "entry",
                id = foundId,
                resource = ""
            });

            urlPath += HttpContext.Current.Request.QueryString
                .ToQueryString(key => !key.Equals("path", StringComparison.InvariantCultureIgnoreCase));

            response.Headers.Location = UrlUtils.FormatUri(urlPath);

            return response;
        }

        [Authorize]
        public async Task<HttpResponseMessage> Post(HttpRequestMessage req, string path, string rel = null)
        {            
            Guid foundId = ControllerUtils.findEntryId(checkPath(path));
            if (foundId == Guid.Empty)
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            var entry = (await EntryFE.TryParsePathAsync(foundId.ToString(), ParsableType.Guid) as CofeSystemInfo);
            if (entry == null)
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            if (String.Equals(rel, "upload", StringComparison.CurrentCultureIgnoreCase))
                return await EntryController.invokeAction(req, foundId, "upload");

            var prop = ControllerUtils.findProperty(entry.Properties, rel);
            if (prop == null)
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            return await EntryController.invokeAction(req, foundId, CofeServices.PropertyDictionary.GetPropertyString(prop));

        }

        //public httpresponsemessage post(string path, string rel = null)
        //{
        //    var retval = get(path, rel);

        //    retval.
        //}
    }
}
